Page({
  data: {
    realName: '',
    idCard: '',
    serviceArea: '',
    experience: '',
    idCardFrontUrl: '',
    idCardBackUrl: '',
    certificationUrl: ''
  },

  onRealNameChange: function(e) {
    this.setData({
      realName: e.detail.value
    });
  },

  onIdCardChange: function(e) {
    this.setData({
      idCard: e.detail.value
    });
  },

  onServiceAreaChange: function(e) {
    this.setData({
      serviceArea: e.detail.value
    });
  },

  onExperienceChange: function(e) {
    this.setData({
      experience: e.detail.value
    });
  },

  onIdCardFrontUpload: function(e) {
    this.setData({
      idCardFrontUrl: e.detail.imageUrl
    });
  },

  onIdCardBackUpload: function(e) {
    this.setData({
      idCardBackUrl: e.detail.imageUrl
    });
  },

  onCertificationUpload: function(e) {
    this.setData({
      certificationUrl: e.detail.imageUrl
    });
  },

  submitCertification: function() {
    // 表单验证
    if (!this.data.realName) {
      wx.showToast({
        title: '请输入真实姓名',
        icon: 'none'
      });
      return;
    }

    if (!this.data.idCard) {
      wx.showToast({
        title: '请输入身份证号',
        icon: 'none'
      });
      return;
    }

    if (!this.data.serviceArea) {
      wx.showToast({
        title: '请输入服务区域',
        icon: 'none'
      });
      return;
    }

    if (!this.data.idCardFrontUrl) {
      wx.showToast({
        title: '请上传身份证正面',
        icon: 'none'
      });
      return;
    }

    if (!this.data.idCardBackUrl) {
      wx.showToast({
        title: '请上传身份证反面',
        icon: 'none'
      });
      return;
    }

    // 提交认证申请
    const app = getApp();
    
    app.request({
      url: '/accounts/technician/certification/',
      method: 'POST',
      data: {
        real_name: this.data.realName,
        id_card: this.data.idCard,
        service_area: this.data.serviceArea,
        experience: this.data.experience,
        id_card_front: this.data.idCardFrontUrl,
        id_card_back: this.data.idCardBackUrl,
        certification: this.data.certificationUrl || ''
      },
      success: (res) => {
        if (res.statusCode === 201) {
          wx.showToast({
            title: '认证申请已提交',
            icon: 'success'
          });
          
          // 跳转到个人资料页面
          setTimeout(() => {
            wx.navigateTo({
              url: '/pages/technician/profile'
            });
          }, 1500);
        } else {
          wx.showToast({
            title: res.data.error || '提交失败',
            icon: 'none'
          });
        }
      },
      fail: () => {
        wx.showToast({
          title: '网络错误',
          icon: 'none'
        });
      }
    });
  }
})